<template>
  <form readonly>
    <div v-if="showNodeForm">
      <!--  customize properties -->
      <el-form
        ref="form"
        label-width="80px"
        v-model="formModel"
        :disabled="readOnly"
      >
        <el-tabs>
          <el-tab-pane
            :label="$t('batch.workflowConfig.form.configurationInfo')"
          >
            <el-row>
              <el-form-item
                :label="$t('batch.missionManage.form.processCode')"
                :required="true"
              >
                <el-input
                  v-model="formModel.nodeCode"
                  @blur.prevent="handleSubmit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                :label="$t('batch.missionManage.form.processName')"
                :required="true"
              >
                <el-input
                  v-model="formModel.label"
                  @blur.prevent="handleSubmit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item :label="$t('batch.workflowConfig.form.errorIgnore')" :required="true">
                <el-select
                  v-model="formModel.errorIgnore"
                  @change="handleSubmit"
                >
                  <el-option
                    v-for="(item, index) in yes_no"
                    :key="index"
                    :label="item.text"
                    :value="item.id"
                    >{{ item.text }}</el-option
                  >
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item :label="$t('batch.workflowConfig.form.executionObject')" :required="true">
                <el-select
                  v-model="formModel.nodeHandler"
                  @change="handleSubmit"
                >
                  <el-option
                    v-for="(item, index) in executorList"
                    :key="index"
                    :label="item.executorName"
                    :value="item.id"
                    >{{ item.executorName }}</el-option
                  >
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item :label="$t('batch.workflowConfig.form.whetherToFragment')" :required="true">
              <el-select v-model="formModel.isSplit" @change="handleSubmit">
                <el-option value="">--{{ $t('batch.missionManage.rules.pleaseSelect') }}--</el-option>
                <el-option
                  v-for="(item, index) in yes_no"
                  :key="index"
                  :label="item.text"
                  :value="item.id"
                  >{{ item.text }}</el-option
                >
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item
                :label="$t('batch.workflowConfig.form.numberRetries')"
                :required="true"
                @change="handleSubmit"
              >
                <el-input
                  v-model="formModel.executeTimes"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                  @blur.prevent="handleSubmit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item :label="$t('batch.workflowConfig.form.expireTime')" :required="true">
                <el-input
                  v-model="formModel.expireTime"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                  @blur.prevent="handleSubmit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item :label="$t('batch.workflowConfig.form.delayedExecution')" :required="true">
                <el-input
                  v-model="formModel.delaySeconds"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                  @blur.prevent="handleSubmit"
                ></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item :label="$t('common.remark')" prop="remark">
                <el-input
                  v-model="formModel.remark"
                  @blur.prevent="handleSubmit"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <div v-if="showEdgeForm">
      <el-form ref="form" label-width="80px" :disabled="readOnly">
        <div style="margin-bottom: 10px"></div>
        <el-form-item :label="$t('batch.workflowConfig.form.expression')">
          <el-input
            v-model="formModel.expression"
            @blur.prevent="handleSubmit"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
  </form>
</template>

<script>
import { queryAllExecutor } from "@/api/batch_app/systemConfig/actuator";
import localEnum from "@/local_enum";
import { cloneDeep } from "lodash";
export default {
  name: "EditorDetailForm",
  inject: ["root"],
  props: ["type", "readOnly"],
  data() {
    return {
      formModel: {},
      tenantCode: "",
      showNodeForm: false,
      showEdgeForm: false,
      maxNodeWidth: 200, // fit long label
      defaultNodeWidth: 80,
      defaultNodeHeight: 48,
      fontSize: 12,
      // 用于关联的线操作
      edgeActionList: [],
      yes_no: [],
      // 执行器列表
      executorList: [],
      params: [],
    };
  },
  mounted() {
    this.yes_no = localEnum.yes_no;
    queryAllExecutor().then((res) => {
      this.executorList = res.result;
    });
    setTimeout(() => {
      const formModel = this.root.propsAPI.getSelected()[0].getModel();
      this.formModel = Object.assign(
        {},
        { shape: "flow-smooth" },
        cloneDeep(formModel) // 防止误编辑
      );
      if (!formModel.errorIgnore) {
        formModel.errorIgnore = 1;
      }
      if (!formModel.delaySeconds) {
        formModel.delaySeconds = 0;
      }

      if (this.type == "edge") {
        if (formModel.nodeType != 2) {
          this.showEdgeForm = true;
        }
      } else {
        if (formModel.nodeType != 2) {
          this.showNodeForm = true;
        }
      }
    }, 10);
  },
  beforeDestroy() {},
  methods: {
    handleSubmit() {
      const { getSelected, executeCommand, update } = this.root.propsAPI;
      const { formModel } = this;
      this.$nextTick(() => {
        const item = getSelected()[0];
        if (!item) return;

        // 自动调整尺寸
        const adjustSize = (model) => {
          if (model.type !== "node" || model.shape !== "flow-rect") {
            return model;
          }
          const canvas = document.createElement("canvas");
          const canvasContext = canvas.getContext("2d");
          canvasContext.font = this.fontSize + "px System";
          const maxWidth = this.maxNodeWidth;
          let label = model.label.replace("\n", "");
          let sourceWidth = this.defaultNodeWidth;
          let sourceHeight = this.defaultNodeHeight;
          const spacing = 10;
          const widthWithSpacing =
            canvasContext.measureText(label).width + spacing;
          model.size = `${sourceWidth}*${sourceHeight}`; // 先恢复默认尺寸

          if (widthWithSpacing <= sourceWidth || sourceWidth >= maxWidth) {
            return model;
          }

          // 自动撑宽
          if (widthWithSpacing <= maxWidth) {
            return {
              ...model,
              size: `${widthWithSpacing}*${sourceHeight}`,
            };
          }

          // 自动折行
          let multilineText = "";
          let multilineCount = 1;
          let multilineTextWidth = 0;

          for (const char of label) {
            const { width } = canvasContext.measureText(char);

            if (multilineTextWidth + width + spacing >= maxWidth) {
              multilineText += "\n";
              multilineTextWidth = 0;
              multilineCount++;
            }

            multilineText += char;
            multilineTextWidth += width;
          }

          return {
            ...model,
            label: multilineText,
            size: `${maxWidth}*${Math.max(
              sourceHeight,
              this.fontSize * multilineCount * 1.2 + spacing
            )}`,
          };
        };

        const newFormModel = adjustSize(formModel);

        executeCommand(() => {
          update(item, newFormModel);
        });

        this.$forceUpdate();
      });
    },
  },
};
</script>

<style lang="less">
hr {
  height: 0;
  border: 0;
  border-top: 1px dashed #ccc;
}
.form-item {
  display: flex;
  font-size: 12px;

  label {
    width: 70px;
    margin-right: 10px;
    text-align: right;
  }
  input {
    width: 160px;
  }
  button {
    width: 160px;
    height: 30px;
    margin: 0 auto;
  }
}
</style>
